package com.business.lgh.naocs.naming.core.pojo;

import com.business.lgh.nacos.api.naming.pojo.Cluster;
import com.business.lgh.nacos.api.naming.pojo.Instance;
import com.business.lgh.nacos.api.naming.pojo.Service;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author lgh
 * @version V1.0
 * @Package com.business.lgh.naocs.naming.core.pojo
 * @date 2020/6/24 5:16 下午
 */
@Data
public class ClusterWrapper extends Cluster {

    /**
     * 持久化节点
     */
    @JsonIgnore
    private Set<InstanceWrapper> persistentInstances = new HashSet<>();

    /**
     * 临时节点
     */
    @JsonIgnore
    private Set<InstanceWrapper> ephemeralInstances = new HashSet<>();

    /**
     * 持有了服务
     */
    private Service service;

    /**
     * 设置服务节点和集群名称
     *
     * @param clusterName
     * @param service
     */
    public ClusterWrapper(final String clusterName, Service service) {
        this.service = service;
        setClusterName(clusterName);
        validate();
    }

    private void validate() {
    }

    public Set<InstanceWrapper> allIps(boolean ephemeral) {
        if (ephemeral) {
            return ephemeralInstances;
        }
        return persistentInstances;
    }

    public List<InstanceWrapper> allIPs() {
        List<InstanceWrapper> allInstances = new ArrayList<>();
        allInstances.addAll(persistentInstances);
        allInstances.addAll(ephemeralInstances);
        return allInstances;
    }

    /**
     * 获取临时节点集合或持久化节点集合
     * @param isEphemeral
     * @return
     */
    public List<InstanceWrapper> allIPs(boolean isEphemeral) {
        return  new ArrayList<>(isEphemeral?ephemeralInstances:persistentInstances);
    }


    public void init() {
    }

    public void updateIps(List<InstanceWrapper> newIps, boolean ephemeral) {
        Set<InstanceWrapper> toUpdateInstances = ephemeral ? ephemeralInstances : persistentInstances;

        //异构下旧有实例集合
        HashMap<String, InstanceWrapper> oldMap = (HashMap<String, InstanceWrapper>) toUpdateInstances.stream()
                .collect(Collectors.toMap(InstanceWrapper::getDatumKey, Function.identity()));

        //TODO 找到交集，并且更新信息，还要找到差集（新实例与死亡实例，用于通知心跳检查器维护检查列表）
        List<InstanceWrapper> updatedIps = intersectionIps(newIps,oldMap);

        //实际直接以新集合覆盖过去就好了
        toUpdateInstances=new HashSet<>(newIps);
        if (ephemeral) {
            ephemeralInstances = toUpdateInstances;
        } else {
            persistentInstances = toUpdateInstances;
        }
    }

    private List<InstanceWrapper> intersectionIps(List<InstanceWrapper> newIps, HashMap<String, InstanceWrapper> oldMap) {
        return null;
    }
}
